package com.admin.education.controllers.api.v1;

import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.common.openId.OpenIdAuthorize;
import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.response.ResponseMessageWithData;
import com.admin.education.common.response.Result;
import com.admin.education.common.utils.OpenIdUtil;
import com.admin.education.dataTransferObject.ServicesExcuteResult;
import com.admin.education.dataTransferObject.user.JwtResponse;
import com.admin.education.dataTransferObject.userInformation.UserInformationTransfer;
import com.admin.education.models.User;
import com.admin.education.services.Interfaces.IUserService;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.Callable;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/v1/auth")
@OpenIdAuthorize
public class AuthController {
    private long ttl;
    public  AuthController(){
        ttl = 1000*60*60*24*365*10;
    }
    @Autowired
    private IUserService userService;
    @PutMapping("{userInformationId}")
    public Callable<IResponseMessage> changeAuth(@PathVariable long userInformationId, HttpServletRequest request){
        return new Callable<IResponseMessage>() {
            @Override
            public IResponseMessage call() throws Exception {
                User user= OpenIdUtil.getUser(request);

                IResponseMessage responseMessage = null;
                ServicesExcuteResult<UserInformationTransfer> result = userService.ChangeAuth(user.getId(),userInformationId);
                if(result.isSuccess()){
                    long nowMillis = System.currentTimeMillis();
                    Date now = new Date(nowMillis);
                    JwtBuilder jwtBuilder= Jwts.builder()
                            .setHeaderParam("typ", "JWT")
                            .setSubject(user.getUserName())
                            .claim("userName", user.getUserName())
                            .claim("userId",user.getId())
                            .claim("auth", JSON.toJSONString(result.getData()))
                            .setIssuedAt(new Date())
                            .setIssuer(user.getUserName())
                            .signWith(SignatureAlgorithm.HS256, "secretkey");

                    long expMillis = nowMillis + ttl;
                    Date exp = new Date(expMillis);
                    jwtBuilder.setExpiration(exp).setNotBefore(now);

                    JwtResponse jwtResponse = new JwtResponse();
                    jwtResponse.setAccess_token(jwtBuilder.compact());
                    jwtResponse.setExpires_in(ttl);
                    jwtResponse.setOpen_id(result.getErrorMessage());
                    jwtResponse.setToken_type("Bearer");

                     responseMessage = new ResponseMessageWithData<JwtResponse>(Result.Success,jwtResponse);
                    return responseMessage;
                }
                else{
                    throw new BadRequestException(result.getErrorMessage());
                }
            }
        };
    }
}
